<?php
/**
 * Created by PhpStorm.
 * User: huihui
 * Date: 2018/8/29
 * Time: 下午6:59
 */

namespace app\index\controller;

use app\admin\model\User;
use app\admin\model\Userhis;
use GatewayClient\Gateway;
use think\Db;
use think\Exception;
use think\Session;
use Workerman\Worker;

class Trade extends Base{

    public function giveTofriends()
    {
        $ismobile = ismobile();
        $fid = input("post.friendid");
        $score = input("post.score");
        $uid = Session::get('user')['id'];
        $fuser = User::get(['username'=>$fid]);

        $user = User::get($uid);
        if ($user['score'] < $score){
            return json(['status'=>-1,'error'=>"账户余额不足"]);
        }
        if (!$fuser){
            return json(['status'=> -1,'error'=>"没有这个好友iD"]);
        }


        try{
            Db::startTrans();
            $user->setDec('score',$score);
            $fuser->setInc('score',$score);

            //送出记录
            $userhis = new Userhis();
            $userhis['gid'] = 0;
            $userhis['uid'] = $uid;
            $userhis['type'] = 2;
            $userhis['data'] = 0 - $score;
            $userhis['comment'] = "赠送好友".$fuser['username']."积分";
            $userhis['create_time'] = date("Y-m-d H:i:s");
            $userhis->save();

            //入账记录
            $userhis = new Userhis();
            $userhis['gid'] = 0;
            $userhis['uid'] = $fuser['id'];
            $userhis['type'] = 2;
            $userhis['data'] = $score;
            $userhis['create_time'] = date("Y-m-d H:i:s");
            $userhis['comment'] = "接收好友".$user['username']."积分";
            $userhis->save();

            Db::commit();
            if (!$ismobile){
                //刷新两个用户的分数面板
                $s['type'] = "score_update";
                $s['data'] = User::get($uid)['score'];
                Gateway::sendToUid($uid,json_encode($s));

                $s['type'] = "score_update";
                $s['data'] = User::get($fid)['score'];
                Gateway::sendToUid($fuser['id'],json_encode($s));
            }

            return json(['status'=>1,'error'=>"赠送成功"]);
        }catch (Exception $e){
            Db::rollback();
            return json(['status'=>-1,'error'=>"赠送失败",'info'=>$e]);
        }



//        return ['status'=>1,"data"=>$_SESSION['uid']];
    }

}